<template>
	<div class="app-content">
		<div class="app-main border--all">
			<div class="plan-view plan-finnal-outline" v-loading="saveArticleLoading">
				<div class="plan-left border--right">
					<div class="finnal-outline--select-article  position--relative">
						<div class="select-article-title vi-view-title">
							<div class="select-article-title-change">{{ articleList.theme }}</div>
							<el-icon class="float--right view-title-option" @click="backOutline" v-if="!articlePager.stageId">
								<Edit />
							</el-icon>
						</div>
						<div class="select-article-outline-view center-position">
							<div class="finnal-outline--select-article position--relative">
								<div class="select-article-content center-position">
									<div class="select-article-view" v-for="content in articleList.content">
										<div class="select-article-content-view">{{ content.section }}</div>
										<div class="select-article-content-view--subsection-parent">
										   <div class="select-article-content-view select-article-content-view--subsection" v-for="subsection in content.subsections">{{ subsection }}</div>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="plan-right app-content" v-loading="articleLoading">
					<div class="app-top app-finnal-outline padding-20">
						<div class="vi-view-title">最终文章</div>
						<div class="buttons margin-t-20">
							<el-button type="primary" plain @click="replaceText(1)">替换</el-button>
							<el-button type="primary" plain @click="replaceText(2)">扩写</el-button>
							<el-button type="primary" plain @click="replaceText(3)">缩写</el-button>
							<el-button type="primary" plain @click="reCreateArticle()">重生</el-button>
							<div class="platform-select-view">
								<el-select
									v-model="platform.value"
									placeholder="请选择平台风格"
								>
									<el-option
										v-for="item in platform.lists"
										:key="item.id"
										:label="item.value"
										:value="item.id"
									/>
								</el-select>
								<el-button type="primary" plain @click="transferPlatform">风格转换</el-button>
							</div>
							<el-button type="primary" plain @click="saveArticle">保存</el-button>
							<el-button type="primary" plain @click="oldPrev" v-if="articlePager.stageId">上一篇</el-button>
							<el-button type="primary" plain @click="oldNext" v-if="articlePager.stageId">下一篇</el-button>
						</div>
					</div>
					<div class="app-main has-finnal-outline padding-20">
						<div class="app-main--editor-wang">
							<cl-editor-wang ref="editorWangRef" v-model="articleValue" />
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
	<el-dialog v-model="replaceModal.visible" @close="closeReplaceModal" width="1200">
		<div class="editor-modal" v-loading="replaceModal.loading">
			<div class="editor-view">
				<edit-div class="editor-content" :contenteditable="true" :content="replaceModal.text"
					@update:content="replaceModal.text = $event"></edit-div>
			</div>
			<div class="buttons float--right">
				<el-button type="primary" plain @click="closeReplaceModal">取消</el-button>
				<el-button type="primary" @click="replaceActive">确认</el-button>
			</div>
		</div>
	</el-dialog>
</template>

<script setup lang="ts" name="work-planning-final-outline">
import { onMounted, reactive, ref } from "vue";
import { router, service,storage } from "/@/cool";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { config } from "/@/utils/global";
import { timeFormat, wholeToParse } from "/@/utils/tools";
import EditDiv from "/@/components/EditDiv.vue";
import { get_platform_type, get_transfer_platform_type } from "/@/utils/dictionary";
let route = useRoute();
let articleList = reactive<any>({});
let articleValue = ref("");
//调整大纲
const backOutline = () => {
	router.back();
}
//转换大纲数据
const getOutlineToString = (checkArticleList: any) => {
	const result = checkArticleList.content.reduce((accumulator: string, element: any) => {
		let string = "";
		string += element.section;
		element?.subsections?.forEach((itemX) => {
			string += "\n\xa0\xa0\xa0\xa0\xa0\xa0" + itemX
		})
		return (accumulator ? accumulator + "\n" : accumulator) + string;
	}, "");
	return { query: checkArticleList.theme, dagang: result };
}
//获取文章
const articleParams = reactive({
	"inputs": {
		"query": "",
		"dagang": "",
		"number": "1000"
	},
	...config.AI_PARAMS
})
let articleLoading = ref(false);
const getArticleContent = async () => {
	articleLoading.value = true;
	let queryContent = routeQuery?.value.content || '';
	let theme: any = routeQuery?.value.theme || "";
	let content: any = wholeToParse(queryContent);
	articleList.theme = theme; articleList.content = content;
	let value: any = getOutlineToString(articleList);
	Object.assign(articleParams.inputs, value);
	let values = await service.base.open.article(articleParams).catch((error) => {
		ElMessage({
			message: error.message || "加载失败",
			type: 'warning',
		})
		articleLoading.value = false;
		return;
	}).finally(() => {
		articleLoading.value = false;
	});
	let data = wholeToParse(values);
	let answerValue: any = data?.answer;
	articleValue.value = answerValue;
}
//通过id文章
const articlePager = reactive({
	page:1,
	size:1,
	stageId:<any>"",
})
const articleContent = ref<any>({});
const outlineContent = ref<any>({});
const maxArticlePage = ref(0)
const getOldArticleList =async () => {
	saveArticleLoading.value = true;
	articlePager.stageId = routeQuery?.value.stage_id || "";
	let values:any = await service.campaign.admin.article.page(articlePager).catch((error) => {
		ElMessage({
			message: error.message || "加载失败",
			type: 'warning',
		})
		saveArticleLoading.value = false;
		return;
	});
	articleContent.value = values.list[0];
	maxArticlePage.value = Math.floor(values.pagination.total/values.pagination.size);
	articleValue.value = articleContent.value.content;
	let outline:any = await service.campaign.admin.outline.page({articleId:articleContent.value.id}).catch((error) => {
		ElMessage({
			message: error.message || "加载失败",
			type: 'warning',
		})
		saveArticleLoading.value = false;
		return;
	});
	saveArticleLoading.value = false;
	outlineContent.value = outline.list[0];
	articleList.theme = outlineContent.value.title; articleList.content = wholeToParse(outlineContent.value.content);
}
//上一篇
const oldPrev = () => {
    if(articlePager.page <= 1){return}
	articlePager.page--;
	getOldArticleList();
}
//下一篇
const oldNext = () => {
	if(articlePager.page >= maxArticlePage.value){return}
	articlePager.page++;
	getOldArticleList();
}
//获取选中元素
const editorWangRef = ref<any>(null);
const replaceContent = (text: string) => {
	editorWangRef.value.Editor.deleteFragment();
	editorWangRef.value.Editor.insertText(text);
}
//选中内容
const requestRequest = async (type: any, text: string) => {
	switch (type) {
		case 1:
			replaceModal.replaceParams.inputs = { content: text };
			return service.base.open.replace(replaceModal.replaceParams);
		case 2:
			replaceModal.replaceParams.inputs = { content: text };
			return service.base.open.expand(replaceModal.replaceParams);
		case 3:
			replaceModal.replaceParams.inputs = { query: text };
			return service.base.open.abbreviation(replaceModal.replaceParams)
	}
}
//替换 1,扩写:2,缩写3
const replaceText = async (type: any) => {
	let text: string = editorWangRef.value.Editor.getSelectionText();
	editorWangRef.value.Editor.addMark("color", "var(--el-color-primary)")
	if (!text) {
		ElMessage({
			message: "请选择一段内容",
			type: 'warning',
		})
		return;
	}
	openReplaceModal(); replaceModal.loading = true;
	let values = await requestRequest(type, text).catch((error) => {
		ElMessage({
			message: error.message || "加载失败",
			type: 'warning',
		})
		replaceModal.loading = false;
		return;
	}).finally(() => {
		replaceModal.loading = false;
	});
	let value = wholeToParse(values);
	if (type == 3) {
		replaceModal.text = value?.answer || "";
	} else {
		replaceModal.text = value?.data?.outputs?.text || "";
	}
}
//修改内容
const replaceActive = () => {
	editorWangRef.value.Editor.removeMark('color');
	replaceContent(replaceModal.text);
	closeReplaceModal();
}
//获取某个替换弹出层
const replaceModal = reactive({
	visible: false,
	loading: false,
	replaceParams: {
		"inputs": {},
		...config.AI_PARAMS
	},
	text: <any>"",
})
const openReplaceModal = () => {
	replaceModal.visible = true;
}
const closeReplaceModal = () => {
	replaceModal.visible = false;
}
//转换平台风格
let platform = reactive({
	value:0,
	lists:get_transfer_platform_type(),
})
let transferParams=reactive({
	"inputs": {
		"query": "",
	},
	...config.AI_PARAMS
})
const transferPlatform =async () => {
	transferParams.inputs.query = editorWangRef.value.Editor.getText();
	articleLoading.value=true;
	let values = await service.base.open.redstyle(transferParams).catch((error) => {
		ElMessage({
			message: error.message || "加载失败",
			type: 'warning',
		})
		articleLoading.value = false;
		return;
	}).finally(() => {
		articleLoading.value = false;
	});
	let data = wholeToParse(values);
	let answerValue: any = data?.answer;
	articleValue.value = answerValue;
}
//保存大纲和文章
let saveArticleLoading = ref(false);
const articleRequest = (editorArcticle:any,planValue:any)=>{
	let nowTime = timeFormat(new Date(), "YYYY-MM-DD HH:mm:ss");
	let userInfo = storage.get("userInfo");
	const ssologinid = routeQuery?.value.ssologinid || "";
	let articleParams = {
		"id":articleContent.value?.id || "",
		"stage_id": planValue.stage_id,
		"title":articleList.theme,
		"content": editorArcticle,
		"generate_time": articleContent.value?.generateTime || nowTime,
		"version": (articleContent.value?.version || 0) + 1 ,
		"creator": ssologinid || userInfo.id,
	}
	if(articleParams.id){
		return new Promise((resolve,reject)=>{
			return service.campaign.admin.article.update(articleParams).then(()=>{
				resolve(articleParams);
			},(error)=>{
				reject(error);
			})
		});
	}else{
		return service.campaign.admin.article.add(articleParams);
	}
}
const outlineRequest = ()=>{
	let userInfo = storage.get("userInfo");
	const ssologinid = routeQuery?.value.ssologinid || "";
	let outlineParams={
		"id":outlineContent.value?.id || "",
		"article_id": articleContent.value.id || "",
		"title":articleList.theme,
		"content": JSON.stringify(articleList.content),
		"version": (outlineContent.value?.version || 0) + 1 ,
		"creator": ssologinid || userInfo.id,
	}
	if(outlineParams.id){
		return new Promise((resolve,reject)=>{
			service.campaign.admin.outline.update(outlineParams).then(()=>{
				resolve(outlineParams);
			},(error)=>{
				reject(error);
			})
		});
	}else{
		return service.campaign.admin.outline.add(outlineParams);
	}
}
const saveArticle = async () => {
	let editorArcticle = editorWangRef.value.Editor.getHtml();
	if (!editorArcticle) {
		ElMessage({
			message: "您的文章还未编辑",
			type: 'warning',
		})
		return;
	}
	let planValue = storage.get("planValue") || {};
	planValue.stage_id = [null,"",undefined].indexOf(planValue?.stage_id) == -1? planValue?.stage_id : -1;
	saveArticleLoading.value = true;
	let articleValue = await articleRequest(editorArcticle,planValue).catch((error) => {
		ElMessage({
			message: error.message || "加载失败",
			type: 'warning',
		})
		saveArticleLoading.value = false;
		return;
	});
	articleContent.value.id = articleValue.id;
	let outlineValue = await outlineRequest().catch((error)=>{
	 ElMessage({
		 message: error.message || "加载失败",
		 type: 'warning',
	 })
	 saveArticleLoading.value=false;
	 return;
	});
	outlineContent.value.id = outlineValue.id;
	saveArticleLoading.value = false;
	let path = "",query={} as any;
	const ssologinid = routeQuery.value?.ssologinid || "";
	let pageType = storage.get("pageType") || "";
	if(pageType == "bespoke"){
		path = "/bespoke/planning-list";
		query = {};
	}else{
		if(ssologinid){
			path = "/work/planning/add-planning";
			query={
				answer : planValue.answer
			};
		}else{
			path = "/work/planning/planning-list";
			query = {
				plan_id:planValue.plan_id,
				startDate:planValue.startDate,
				endDate:planValue.endDate,
			};
		}
	}
	router.push({
		path: path,
		query: query
	})
	storage.remove("outline");//删除缓存大纲
	storage.remove("planValue");//删除策案数据
}
const reCreateArticle = () => {
	getArticleContent();
}
let routeQuery:any = ref(null);
onMounted(() => {
	routeQuery.value = route.query;
	routeQuery.value.content = storage.get("outline") || "";
	let stage_id = routeQuery?.value.stage_id || "";
	if(stage_id){
		getOldArticleList();
	}else {
		getArticleContent();
	}
})
</script>

<style scoped lang="scss">
.select-article-title-change {
	width: 360px;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.plan-finnal-outline {
	.plan-left {
		width: 400px;
	}
}

.has-finnal-outline {
	top: 104px;
}

.select-article-title {
	display: flex;
	width: 96%;

	&.width-1 {
		width: 120px;
	}
}

.finnal-outline {
	&--select-article {
		width: 100%;
		height: 100%;
		padding: 20px;
		box-sizing: border-box;

		.select-article-outline-view {
			width: 100%;
			height: 100%;
			max-height: calc(100% - 80px);
			overflow: hidden;
			padding: 20px;
			box-sizing: border-box;
		}

		.select-article-content {
			width: calc(100% - 40px);
			height: 100%;
			max-height: calc(100% - 10px);
			overflow: hidden;
			overflow-y: auto;
		}

		::-webkit-scrollbar {
			display: none;
		}

		.select-article-content-title,
		.select-article-content-view {
			width: auto;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
			font-weight: 700;
			color: #000000;
			font-size: 20px;
			line-height: 24px;
			margin-top: 10px;
			margin-bottom: 10px;
			cursor: pointer;
			padding: 10px;
			word-break: break-all;

			&.active {
				color: var(--el-color-primary);
			}

			&--subsection-parent{
				width: 100%;
				font-size: 16px;
				padding-left: 2em;
				box-sizing: border-box;
			}
			&--subsection {
				font-size: 16px;
				line-height: 20px;
				margin-top: 0px;
				margin-bottom: 0px;
				color: #333333;
			}
		}

		.select-article-footer {
			bottom: 40px;
		}
	}
}
//平台
.platform-select-view{
	width: 320px;
	overflow: hidden;
	display: inline-flex;
	justify-content: center;
	align-items: center;
	line-height: 1;
	height: 32px;
	padding: 0px 15px;
	vertical-align: middle;
	:deep(.el-select__wrapper){
		box-shadow: 0 0 0 1px var(--el-color-primary-light-5) inset;
	}
	:deep(.el-select__caret){
		color: var(--el-color-primary-light-5);
	}
	:deep(.el-select__selected-item){
		color: var(--el-color-primary);
	}
}
</style>
